#include "user.h"
#include "login.h"
#include <string>

using namespace Login;
using namespace User;
extern Database::userDatabase &userdb;
extern Database::bookDatabase &bookdb;

user::user(string name) : username(name)
{
	
}

void user::start()
{
	char operation;
	system("cls");
	cout << "Hello, " << username << endl;
	for (int i = 0; i <= 150000000; i++);
	do
	{
		cout << "1.Search book" << endl;
		cout << "2.Check out the borrowing book" << endl;
		cout << "3.Borrow book" << endl;
		cout << "4.Return book" << endl;
		cout << "5.Change Password" << endl;
		cout << "6.Quit" << endl;
		cin.sync();
		operation = _getch();
		switch (operation)
		{
		case '1':
			searchBook(); break;
		case '2':
			checkBorrowed(); break;
		case '3':
			borrowBook(); break;
		case '4':
			returnBook(); break;
		case '5':
			changePassword(); break;
		case '6': case 27:
			return;
		}
		system("cls");
	} while (true);
}

void user::searchBook()
{
	string name;
	cout <<endl<< "The book name:";
	getline(cin, name);
	bookdb.search(name);
}

void user::checkBorrowed()
{
	userdb.checkBorrowed(username);
	_getch();
}

void user::borrowBook()
{
	string name;
	int result;
	cout <<endl<< "The book name:";
	getline(cin, name);
	result = bookdb.borrowBook(username, name);
	if (result == 0)
		cout << "Couldn't find the book \"" << name << "\"." << endl;
	else if (result == 1)
		cout << "The book \"" << name << "\" has already been rent out." << endl;
	else if (result == 2)
		cout << "You can't borrow more book." << endl;
	else if (result == 3)
		cout << "Operation complete." << endl;
	_getch();
}

void user::returnBook()
{
	string name;
	int result;
	cout <<endl<< "The book name:";
	getline(cin, name);
	result = bookdb.returnBook(username, name);
	if (result == 0)
		cout << "Couldn't find the book \"" << name << "\"." << endl;
	else if (result == 1)
		cout << "You didn't borrow the book \"" << name << "\"." << endl;
	else
		cout << "Operation complete." << endl;
	_getch();
}

void user::changePassword()
{
	char *first = 0, *second = 0;
	unsigned char *password;
	bool valid = false;
	system("cls");
	cout << "Input the old password:" ;
	while (userdb.check(username, getMD5(getPassword())) == 1)
	{
		system("cls");
		cout << "Wrong Password" << endl;
		cout << "Input the password:";
	}
	while (!valid)
	{
		cout << "Input the new password:";
		first = getPassword();
		cout << "Repeat the password:";
		second = getPassword();
		valid = true;
		for (int i = 0; i <= 15; i++)
			if (first[i] != second[i])
				valid = false;
		if (valid==false)
		{
			system("cls");
			cout << "The password does't match"<<endl;
		}
	}
	password = getMD5(first);
	if (first)
		delete first;
	if (second)
		delete second;
	userdb.changePassword(username, password);
	cout << "Change sucessfully.";
	for (int i = 0; i <= 150000000; i++);
}

user::~user()
{
	cout << "Goodbye, " <<username<< endl;
	for (int i = 0; i <= 200000000; i++);
}